package system

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/app/business/api/internal/repository/system"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzsystemappversion"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"time"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemVersionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemVersionListLogic - 查询版本列表
func NewSystemVersionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemVersionListLogic {
	return &SystemVersionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemVersionListLogic) SystemVersionList(req *types.SystemVersionListRequest) (resp *types.SystemVersionListResponse, err error) {
	// 创建实例
	versionDao := system.NewSystemVersionDao(l.ctx, l.svcCtx)

	// 兼容老版本，默认查慧赚生活
	if req.AppPackageName == "" {
		req.AppPackageName = constant.AppPackageName
	}

	// 查询版本列表
	versionConditions := make([]predicate.HzSystemAppVersion, 0)
	versionConditions = append(versionConditions, hzsystemappversion.DeleteAtIsNil())
	versionConditions = append(versionConditions, hzsystemappversion.AppPackageNameEQ(req.AppPackageName))
	if req.AppPlatform != 0 {
		versionConditions = append(versionConditions, hzsystemappversion.AppPlatformEQ(req.AppPlatform))
	}
	if len(req.AppVersion) > 0 {
		versionConditions = append(versionConditions, hzsystemappversion.AppVersionGT(req.AppVersion))
	}

	// 获取版本信息
	versionList, err := versionDao.SystemVersionDaoConditionsAll(versionConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("获取版本信息失败：%v", err.Error()))
	}

	// 找出 SdkUpdateType 为 1（wgt）和 2（apk）下 Version 最大的元素并转换为 AppVersionInfo(使用自定义比较函数)
	maxWgtVersion := l.handlerConvertToAppVersionInfo(lo.MaxBy(lo.Filter(versionList, func(item *ent.HzSystemAppVersion, _ int) bool {
		return item.AppSdkUpdateType == constant.Wgt
	}), func(a, b *ent.HzSystemAppVersion) bool {
		return common.CompareVersions(a.AppVersion, b.AppVersion) > 0
	}))
	maxApkVersion := l.handlerConvertToAppVersionInfo(lo.MaxBy(lo.Filter(versionList, func(item *ent.HzSystemAppVersion, _ int) bool {
		return item.AppSdkUpdateType == constant.Apk
	}), func(a, b *ent.HzSystemAppVersion) bool {
		return common.CompareVersions(a.AppVersion, b.AppVersion) > 0
	}))

	// 组装数据
	list := make([]*types.SystemVersionInfo, 0)
	if maxWgtVersion != nil {
		list = append(list, maxWgtVersion)
	}
	if maxApkVersion != nil {
		list = append(list, maxApkVersion)
	}

	// 返回数据
	resp = &types.SystemVersionListResponse{
		List: list,
	}

	return resp, nil
}

// handlerConvertToAppVersionInfo - 构造返回详情
func (l *SystemVersionListLogic) handlerConvertToAppVersionInfo(item *ent.HzSystemAppVersion) *types.SystemVersionInfo {
	if item == nil {
		return nil
	}
	return &types.SystemVersionInfo{
		Id:                    int64(item.ID),
		AppPackageName:        item.AppPackageName,
		AppVersion:            item.AppVersion,
		AppPlatform:           item.AppPlatform,
		AppVersionTitle:       item.AppVersionTitle,
		AppForceUpdateType:    item.AppForceUpdateType,
		AppHotUpdateType:      item.AppHotUpdateType,
		AppPublishStatus:      item.AppPublishStatus,
		AppUpdateDownloadUrl:  item.AppUpdateDownloadURL,
		AppVersionDescription: item.AppVersionDescription,
		AppSdkUpdateType:      strconv.FormatInt(item.AppSdkUpdateType, 10),
		CreatedAt:             time.Unix(item.CreatedAt, 0).Format(time.DateTime),
		UpdateAt:              time.Unix(item.UpdateAt, 0).Format(time.DateTime),
	}
}
